package com.hulk.ratel.config.logback;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

import com.google.common.base.Strings;

import com.hulk.ratel.common.util.IDWorkerRadix;
import lombok.extern.slf4j.Slf4j;


import org.slf4j.MDC;

/**
 * @Author: hulk
 * @Date: 2018/7/4 17:57
 */
@Slf4j
public class TraceLogIdConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent event) {
        try {
            String mdc_trace_id = event.getMDCPropertyMap().get("mdc_trace_id");
            if (Strings.isNullOrEmpty(mdc_trace_id)) {
                String v = new StringBuilder(Thread.currentThread().getId()+"-").append("<").append(IDWorkerRadix.getDtmId().toUpperCase()).append(">").toString() ;
                MDC.put("mdc_trace_id", v);
                return v;
            }
            return mdc_trace_id;
        } catch (RuntimeException e) {
            log.error("TraceLogIdConverter error", e);
            return "";
        }
    }
}
